package com.boy.service.impl;

import com.boy.commonutils.handler.WhdException;
import com.boy.entity.Code;
import com.boy.mapper.CodeMapper;
import com.boy.service.MailService;
import com.boy.tool.enumClass.ExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author whd
 * @date 2024/06/06 11:35:07
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private CodeMapper codeMapper;

    @Value("${admin.email}")
    private String adminEmail;

    /**
     * 发送信息邮件
     *
     * @param to 收件人
     * @throws MessagingException
     */
    @Transactional
    @Override
    public void sendMail(String to) {
        try {
            Code code = new Code();
            code.setEmail(to);
            int c = (int) ((Math.random() * 9 + 1) * 100000);
            code.setCode(String.valueOf(c));
            log.info("发送给邮箱" + to + "的验证码为:" + c);
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //组装
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            //即为邮件发送者，一般设置在配置文件中
            mimeMessageHelper.setFrom(adminEmail);
            mimeMessageHelper.setTo(to);
            String content = "<p>心语树洞您的登录验证码是:" + c + "</p>";
            //邮件主题
            mimeMessageHelper.setSubject("心语树洞");
            //邮件内容
            mimeMessageHelper.setText(content, true);
            mailSender.send(mimeMessage);
            codeMapper.deleteByEmail(code.getEmail());
            codeMapper.insert(code);
        } catch (MessagingException e) {
            throw new WhdException(ExceptionCode.SYSTEM_RUN_EXCEPTION, "发送邮件失败");
        }
    }

}
